import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import _ from 'underscore';
import ModalBehavior from '../../base/behaviors/ModalBehavior';
import SelectWidget from '../../widgets/SelectWidget';

const template = require('./templates/EntryDuplicateForm.mustache');

const Label = Mn.View.extend({
    template: _.template('<div class="alert alert-error"><%- message %></div>'),
    templateContext(){
        return {message: this.getOption('message')}
    }
})
const EntryDuplicateForm = Mn.View.extend({
    behaviors: [ModalBehavior],
    template: template,
    regions: {
        message: '.message-container',
        sheets: '.field-sheets'
    },
    ui: {
        form: "form",
        submit: 'button[type=submit]',
        cancel: 'button[type=reset]'
    },
    events: {
        "click @ui.submit": "onSubmit",
        'submit @ui.form': "onSubmit",
        "click @ui.cancel": "onCancelForm",
    },
    childViewEvents: {},
    childViewTriggers: {},
    initialize(){
        this.config = Radio.channel('config');
        this.facade = Radio.channel('facade');
    },
    onSubmit(event){
        event.preventDefault();
        const select = this.getChildView('sheets');
        const sheetId = select.getCurrentValue();
        if (!sheetId){
            this.showChildView('message', new Label({'message': "Veuillez choisir une feuille statistiques"}));
        } else {
            let request = this.facade.request('entry:duplicate', this.model, sheetId);
            request.then(() => this.onSuccessSync());
        }
    },
    onSuccessSync(){
        this.triggerMethod('modal:close');
    },
    onCancelForm(){
        this.triggerMethod('modal:close');
    },
    templateContext(){
        // Collect data sent to the template (model attributes are already transmitted)
        return {title: "Dupliquer l'entrée statistique " + this.model.get('title')};
    },
    onRender(){
        this.showChildView('sheets', new SelectWidget({
            label: "Vers la feuille de statistiques",
            options: this.getOption('sheets'),
            field_name: 'sheet',
            required: true,
            id_key: 'id',
            label_key: 'title',
            placeholder: '',
        }
        ));
    }
});

export default EntryDuplicateForm
